import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import Login from '@/views/Login.vue';
import Chat from '@/views/Chat.vue';

const routes = [
  { path: '/', redirect: '/home' },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/chat/:id?',
    name: 'Chat',
    component: Chat,
    props: (route: { params: { id?: string } }) => ({ id: route.params.id, isDirectAccess: !route.params.id }),
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 尝试从本地存储恢复用户信息
  if (!userStore.isLoggedIn) {
    userStore.restoreUserInfo();
  }
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    if (userStore.isLoggedIn) {
      // 已登录，允许访问
      next();
    } else {
      // 未登录，重定向到登录页面
      next('/login');
    }
  } else {
    // 不需要认证的页面
    if (to.path === '/login' && userStore.isLoggedIn) {
      // 已登录用户访问登录页面，重定向到首页
      next('/home');
    } else {
      next();
    }
  }
});

export default router;
